import { apiPowerSharing, apiHelpSharingDetails, apiShareCountdown, apiClickHelp, helpSharingDetails, getUpdateLevelByUid, apiMemberIndex } from '../../api/index'
import { submitFromData } from '../../common/js/mixin'
/**
 * 判断助力状态
 * is_del == 0 && share_time == 0 && number == 0订单还未发起
 * is_del == 0 && share_time > 0 && number != sum 订单进行中
 * is_del == 0 && number == sum 助力结束且成功
 * is_del == 1  && sum != number 助力结束且失败
 */

let timer
let page = {
  data: {
    sourceid: 0,
    commend: false,
    helpDetails: {},
    leftTime: '',
    // 可助力
    helpSure: true,
    hasHelp: true,
    noHelp: true,
    money: '', // 赚取的佣金
    helpType: 1, // 1、自己进入  2、自己从助力列表进入 3、他人进入
    status: 1, // 1、订单还未发起 2、订单进行中 3、助力结束且成功 4、助力结束且失败
    finshed: false // 已完成订单,
  },
  // 判断是否授权
  changeAuthStatus (e) {
    this.setData({
      commend: e.detail.status
    })
    this.init()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    if (options.help_list) {
      this.helps = options
      this.getUserShare()
    }
    if (options.data) {
      this.helps = JSON.parse(options.data)
    }
    if (options.id) {
      this.helpId = options.id
    }
    // 分享链接中source_uid
    this.sid = options.source_uid && Number(options.source_uid)
    // 判断是否需要授权
    let commend
    if (!this.sid) {
      // 自己进入
      commend = false
      this.init()
    } else {
      // 分享进入
      commend = true
    }
    this.getUserInfo()
    this.setData({
      isIphoneX: getApp().globalData.isIphoneX,
      commend
    })
  },
  init () {
    // 发起人uid
    this.mineId = parseInt(wx.getStorageSync('uid'))
    getUpdateLevelByUid({ source_uid: this.sid }).then(
      res => {
        console.log(res)
      }
    )
    if (this.helps && this.helps.formList) {
      // 从助力列表进入
      this.getHeplDetail()
    } else {
      var obj = {}
      if (this.sid) {
        // 从分享的微信进入
        obj = {
          helpType: this.sid === this.mineId ? 2 : 3,
          sourceid: this.sid
        }
      } else {
        // 从微信通知进入
        obj = {
          helpType: 1
        }
      }
      this.setData(obj)
      this.getUserShare()
    }
  },
  judgeStatus (data) {
    let status
    if (data.is_del === 0 && data.share_time === 0 && data.number === 0) {
      status = 1
    } else if (data.is_del === 0 && data.share_time > 0 && data.number !== data.sum) {
      status = 2
    } else if (data.is_del === 0 && data.number === data.sum) {
      status = 3
    } else if (data.is_del === 1 && data.number !== data.sum) {
      status = 4
    }
    this.setData({
      status
    })
  },
  judgeHadHelped (data) {
    for (var i = 0; i < data.help_user.length; i++) {
      let item = data.help_user[i]
      if (this.mineId === item.uid) {
        this.setData({
          noHelp: false,
          money: item.money
        })
      }
    }
  },
  judgeFinshed (data) {
    if (data.order_id > 0) {
      this.setData({
        finshed: true
      })
    }
  },
  // 助力详情
  getHeplDetail (notShowLoading) {
    apiPowerSharing(this.helps).then(
      res => {
        if (res.data.share_time) {
          this.endTime = res.data.share_time + res.data.minutes * 60
          this.nowTime = new Date().getTime() / 1000
          if (this.endTime > this.nowTime) {
            this.timeDown()
          }
        }
        wx.stopPullDownRefresh()
        if (res.data.sum === res.data.number) {
          clearTimeout(timer)
        }
        // 最长名字长度4
        if (res.data.share_user_info.nick_name.length > 4) {
          res.data.share_user_info.nick_name = res.data.share_user_info.nick_name.substr(0, 4) + '...'
        }
        this.judgeStatus(res.data)
        this.judgeFinshed(res.data)
        this.setData({
          helpDetails: res.data
        })
      }
    )
  },
  // 点击为他助力
  helpGoods (e) {
    this.setData({
      hasHelp: false
    })
    let data = []
    data.push = e.detail.formId
    if (data.length > 0) {
      return
    }
    apiClickHelp({ id: this.data.helpDetails.id }).then(
      res => {
        wx.showToast({
          title: res.data
        })
        this.getUserShare()
        this.setData({
          helpSure: false,
          noHelp: false,
          common: res.data // 佣金
        })
        if (this.sid) {
          this.getUserShare()
        } else {
          this.getHeplDetail()
        }
      }).catch(res => {
      wx.showToast({
        title: res.data.message,
        icon: 'none',
        mask: true,
        duration: 2000,
        complete: () => {
        }
      })
      setTimeout(() => {
        if (this.sid) {
          this.getUserShare(true)
        } else {
          this.getHeplDetail()
        }
      }, 1500)
    })
    this._submitFrom(e.detail.formId)
  },
  timeDown () {
    let s = this.endTime - new Date().getTime() / 1000
    if (s > 0) {
      timer = setTimeout(() => {
        var min = Math.floor(s / 60 % 60)
        var sec = Math.floor(s % 60)
        min = this.add(min)
        sec = this.add(sec)
        let showTime
        if (min > 0 || sec > 0) {
          showTime = `${min}分${sec}秒`
        } else {
          showTime = 0
          this.getUserShare()
        }
        this.setData({
          showTime
        })
        s--
        if (s <= 0) {
          clearTimeout(timer)
          this.onRefresh()
        } else {
          this.timeDown(s)
        }
      }, 1000)
    }
  },
  add (m) {
    return m < 10 ? '0' + m : m
  },
  // 助力进入分享
  getUserShare (notShowLoading) {
    apiHelpSharingDetails({ id: this.helpId, source_uid: this.data.sourceid || '', loading: notShowLoading }).then(
      res => {
        console.log(res)
        if (res.data.share_user_info.nick_name.length > 4) {
          res.data.share_user_info.nick_name = res.data.share_user_info.nick_name.substr(0, 4) + '...'
        }
        if (res.data.share_time) {
          this.endTime = res.data.share_time + res.data.minutes * 60
          this.nowTime = new Date().getTime() / 1000
          if (this.endTime > this.nowTime) {
            this.timeDown()
          }
        }
        this.setData({
          helpDetails: res.data
        })
        this.judgeStatus(res.data)
        this.judgeHadHelped(res.data)
        this.judgeFinshed(res.data)
        if (this.data.showTime === 0 && this.data.helpDetails.sum !== this.helpDetails.number) {
          this.helps = {
            id: res.data.id,
            goods_id: res.data.goods_id,
            number: res.data.sum
          }
          this.getHeplDetail()
        }
      }
    ).catch(res => {

    })
  },
  // 点击完成订单
  orderSure () {
    wx.navigateTo({
      url: `../ass-goods-sure/ass-goods-sure?data=${JSON.stringify(this.data.helpDetails)}`
    })
  },
  toBy () {
    wx.navigateTo({
      url: `../ass-goods-sure/ass-goods-sure?data=${JSON.stringify(this.data.helpDetails)}`
    })
  },
  toHelpList () {
    wx.navigateTo({
      url: `../assistance/assistance`
    })
  },
  // 进入商品详情
  toGoodsDetail () {
    let help = {
      number: this.data.helpDetails.sum,
      id: this.data.helpDetails.sum,
      uid: this.data.helpDetails.uid
    }
    wx.navigateTo({
      url: `../goods-detail/goods-detail?id=${this.data.helpDetails.goods_id}&goods_type=1&help=${JSON.stringify(help)}`
    })
  },
  // 跳转规则
  toAssRule () {
    wx.navigateTo({
      url: '../assistance-rule/assistance-rule'
    })
  },
  // 返回首页
  goHome () {
    wx.switchTab({
      url: '../shopping/shopping'
    })
  },
  // 查看订单详情
  lookOrder () {
    wx.navigateTo({
      url: '../order-detail/order-detail?id=' + this.data.helpDetails.order_id
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () {
    clearTimeout(timer)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onRefresh () {
    helpSharingDetails({
      id: this.data.helpDetails.id
    }).then(res => {
      if (res.data.share_time) {
        this.endTime = res.data.share_time + (res.data.minutes) * 60
        this.nowTime = new Date().getTime() / 1000
        if (this.endTime > this.nowTime) {
          this.timeDown()
        }
      }
      wx.stopPullDownRefresh()
      // 最长名字长度4
      if (res.data.share_user_info.nick_name.length > 4) {
        res.data.share_user_info.nick_name = res.data.share_user_info.nick_name.substr(0, 4) + '...'
      }
      this.judgeStatus(res.data)
      this.judgeFinshed(res.data)
      this.judgeHadHelped(res.data)
      this.setData({
        helpDetails: res.data
      })
    })
  },
  onPullDownRefresh () {
    this.onRefresh()
  },
  getUserInfo () {
    apiMemberIndex().then(
      res => {
        this.userInfo = res.data.user_info.uid
      }
    )
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {
    // 获取倒计时
    apiShareCountdown({ id: this.data.helpDetails.id }).then(res => {
      this.getHeplDetail()
    })
    let imageUrl = this.data.helpDetails.goods_info.pic_cover_big
    return {
      title: '助力好友，即可拿佣金',
      imageUrl,
      path: `/pages/assistance-detail/assistance-detail?id=${this.data.helpDetails.id}&source_uid=${this.userInfo}`
    }
  }
}
submitFromData(page)
Page(page)
